<template>

  <div class="app-container">

    <el-form :inline="true" :model="queryForm" class="demo-form-inline" >
<!--      <el-form-item style="margin-bottom:10px;">
        <el-input v-model="queryForm.keywords" prefix-icon="el-icon-search" placeholder="服务名" style="width: 18.75rem;" />
      </el-form-item> -->
      <el-form-item style="margin-bottom:10px;">
        <!-- <el-button type="primary" icon="el-icon-refresh"  size="mini" :loading="loading" @click="handleInit">初始化</el-button> -->
        <el-button type="danger" icon="el-icon-switch-button"   :loading="loading" @click="restartGPU" plain>重启</el-button>
      </el-form-item>
    </el-form>

    <el-table
      :data="tableData"
      border
      empty-text="暂无数据."
      style="width: 100%">
      <el-table-column
        type="selection"
        width="40">
      </el-table-column>
      <el-table-column
            label="序号"
            width="100"
            prop="index"
            >
            <template slot-scope="scope">
              GPU-{{scope.row.index}}
            </template>
          </el-table-column>


<!--      <el-table-column
        prop="id"
        label="id"
        >
      </el-table-column> -->

      <el-table-column
        prop="name"
        label="名称"
        >
      </el-table-column>

      <el-table-column
        prop="memoryTotal"
        label="显存"
        >
      </el-table-column>

<!--      <el-table-column
        prop="memoryUsed"
        label="已用"
        >
      </el-table-column>


      <el-table-column
        prop="memoryFree"
        label="空闲"
        >
      </el-table-column> -->

      <el-table-column
        prop="percentage"
        label="使用状态"
        >
        <template slot-scope="scope">
        <div class="progress" >
          <div  class="progress-bar progress-bar-striped bg-info progress-bar-animated" style="width: 100%;">
              空闲 {{scope.row.limit -  scope.row.used }}
          </div>
        </div>
        </template>
      </el-table-column>

      <el-table-column prop="enabled" label="是否启用" >
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.enabled"
            active-value="1"
            inactive-value="0"
            :loading="loading"
            @change="handleOnChange(scope.row)"
            >
          </el-switch>

        </template>
      </el-table-column>

      <el-table-column prop="limit" label="限制路数" width="150" >
        <template slot-scope="scope">
         <el-input-number :min="1" :max="2" :loading="loading"   @change="handleOnChange(scope.row)"  v-model="scope.row.limit" style="width: 110px;"/>
        </template>
      </el-table-column>


    </el-table>

    <el-row>
      <el-col :span="24">
        <div align="right" style="margin-top: 0.3125rem;">
          <el-pagination background layout="prev, pager, next" :current-page="page.cur" :page-size="page.limit" :total="page.total" @current-change="handleCurrentChange" />
        </div>
      </el-col>
    </el-row>

    <!--编辑框-->
    <info-dialog
      v-if="editDialog.visible"
      :properties="editDialog"
      @closed="close"
      @refresh="load"
    />

    <SignalingDialog
      v-if="signalingDialog.visible"
      :properties="signalingDialog"
      @closed="closeSignaling"
      @refresh="load"
    />

    <RelayDialog
      v-if="relayDialog.visible"
      :properties="relayDialog"
      @closed="closeRelay"
      @refresh="load"
    />


  </div>
</template>

<script>
  import InfoDialog from './components/InfoDialog.vue'
  import SignalingDialog from './components/SignalingDialog.vue'
  import RelayDialog from './components/RelayDialog.vue'


  import {
    hasPermission
  } from '@/utils/permission'
  import {
    findGPUList,
    deleteById,
    initGPU,
    saveGPU,
    restartGPU
  } from '@/api/cloud/gpu'
  import {
    isOk
  } from '@/utils/request'
  export default {
    name:'Project',
    components: {
      InfoDialog,
      SignalingDialog,
      RelayDialog,
    },
    data() {
      return {
        loading:false,
        queryForm: {
          keywords: undefined,
          status: '',
          orgId: ''
        },
        page: {
          cur: 1,
          limit: 50,
          total: 0
        },
        tableData: [],
        editDialog: {
          visible: false,
          type: '0',
          data: {}
        },
        signalingDialog: {
          visible: false,
          type: '0',
          data: {}
        },
        relayDialog: {
          visible: false,
          type: '0',
          data: {}
        },
        intervalId :null,
        customColor: '#17a2b8',
        customColors: [
          {color: '#17a2b8', percentage: 0},
          {color: '#17a2b8', percentage: 20},
          {color: '#ffc107', percentage: 40},
          {color: '#ff7a06', percentage: 60},
          {color: '#fa5133', percentage: 80},
          {color: '#f50000', percentage: 100}
        ]
      }
    },
    created() {
      this.load();
      //第一次clearInterval,作为保险避免可能存在的intervalId对后面造成影响
      clearInterval(this.intervalId);
      //设置setInterval()每5000ms调用一次tableList()，刷新数据
      // this.intervalId = setInterval(() => {
      //    this.load();
      // }, 2000);

    },
    methods: {
      indexMethod(index) {
        return index +1;
      },
      onQuerySubmit(event) {
        this.load()
      },
      onReset(event) {
        this.queryForm.keywords=undefined;
        this.queryForm.status='';
        this.load()
      },
      isEditMode(row) {
        return row.meta.isEditMode
      },
      setEditMode(row, status) {
        console.log(status)
        row.meta.isEditMode = status
      },
      handleOnChange(row){
        this.handleSave(row);
      },
      load(){
        this.loading=true
        findGPUList({
          cur: this.page.cur,
          limit: this.page.limit,
          keywords: this.queryForm.keywords,
        }).then(rsp => {
          if(isOk(rsp)){
            const _data = rsp.result
            this.page.total = _data.totalRow
            _data.list.forEach(item => {
                item.meta = {
                  isEditMode: false,
                }
            })
            this.tableData = _data.list
          }
        }).catch(err => {
          console.log(err);
        })
        .finally(() => {
          this.loading = false
        })
      },
      close: function(e) {
        this.editDialog.visible = false
        this.editDialog.data = {}
        this.load()
      },
      handleCurrentChange(cur) {
        this.page.cur = cur
        this.load()
      },
      handleSave(row){
        saveGPU({
          id:row.id,
          limit:row.limit,
          enabled:row.enabled,
        }).then(rsp => {
          if (isOk(rsp)) {
            this.load()
          }
        })
      },
      handleInit: function(data) {
        this.$confirm('若服务正在运行，可能会受影响，确认初始化吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.loading = true
          initGPU({
          }).then(response => {
            this.$message({
              message: response.message,
              type: 'success',
              duration: 500
            })
            this.load()
          }).catch(err => {
            console.log(err);
          })
          .finally(() => {
            this.loading = false
          })
        })
      },
      restartGPU: function(data) {
        this.$confirm('若服务正在运行，可能会受影响，确认重启吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.loading = true
          restartGPU({
          }).then(response => {
            this.$message({
              message: response.message,
              type: 'success',
              duration: 500
            })
            this.load()
          }).catch(err => {
            console.log(err);
          })
          .finally(() => {
            this.loading = false
          })
        })
      },
      handleAdd: function(e) {
        this.editDialog.visible = true
        this.editDialog.type = '0'
      },
      handleDelete: function(data) {
        this.$confirm('若服务正在运行，将自动停止，确认删除【' + data.name + '】吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.loading = true
          deleteById({
            id: data.id
          }).then(response => {
            this.$message({
              message: '删除成功',
              type: 'success',
              duration: 500
            })
            this.load()
          }).catch(err => {
            console.log(err);
          })
          .finally(() => {
            this.loading = false
          })
        })
      },
      handleRestart: function(data) {
        this.$confirm('重启服务，将会影响正在使用该服务的用户，确认重启【' + data.name + '】吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.loading = true
          restartServer({
            id: data.id
          }).then(response => {
            this.$message({
              message: '成功',
              type: 'success',
              duration: 500
            })
            this.load()
          }).catch(err => {
            console.log(err);
          })
          .finally(() => {
            this.loading = false
          })
        })
      },
      handleEdit: function(data) {
        if('signaling'==data.type){
          this.handleEditSignaling(data);
        }
        else if('relay'==data.type){
          this.handleEditRelay(data);
        }
      },
      createSignalingServer(){
        this.loading=true
        createSignalingServer({
        }).then(rsp => {
          if(isOk(rsp)){
            this.$message({
              type: 'success',
              message:rsp.message
            })
            this.load();
          }
          this.loading = false
        }).catch(err => {
          console.log(err);
        })
        .finally(() => {
          this.loading = false
        })
      },
      createRelayServer(){
        this.loading=true
        createRelayServer({
        }).then(rsp => {
          if(isOk(rsp)){
            this.$message({
              type: 'success',
              message:rsp.message
            })
            this.load();
          }
          this.loading = false
        }).catch(err => {
          console.log(err);
        })
        .finally(() => {
          this.loading = false
        })
      },
      handleEditSignaling: function(data) {
        this.signalingDialog.visible = true
        this.signalingDialog.type = '1'
        this.signalingDialog.data = data
      },
      closeSignaling: function(e) {
        this.signalingDialog.visible = false
        this.signalingDialog.data = {}
        this.load()
      },
      handleEditRelay: function(data) {
        this.relayDialog.visible = true
        this.relayDialog.type = '1'
        this.relayDialog.data = data
      },
      closeRelay: function(e) {
        this.relayDialog.visible = false
        this.relayDialog.data = {}
        this.load()
      },
/*      format(percentage) {
        return percentage === 100 ? '满' : `${percentage}%`;
      } */
    },
    destroyed() {
      //clearInterval(this.intervalId);
    }
  }
</script>

<style lang="scss" >

  .progress {
      width: 100%;
      height: 40px;
      background: #e9ecef;
      border-radius: 5px;
      -webkit-border-radius: 5px;
      overflow: hidden;
      text-align: center;

      .progress-bar{
        height: 100%;
        line-height: 40px;
        overflow: hidden;
        text-align: center;
        color: #fff;
      }

      .progress-bar-striped {
            background-image: linear-gradient(45deg,hsla(0,0%,100%,.15) 25%,transparent 0,transparent 50%,hsla(0,0%,100%,.15) 0,hsla(0,0%,100%,.15) 75%,transparent 0,transparent);
            background-size: 1rem 1rem;
        }

      .bg-info {
          background-color: #17a2b8;
      }

      .progress-bar-animated {
          animation: progress-bar-striped 1s linear infinite;
          -webkit-animation: progress-bar-striped 1s linear infinite;
      }

  }






</style>
